package com.project.demo.controller;

import com.project.demo.entity.UserNotifications;
import com.project.demo.entity.User;
import com.project.demo.service.UserNotificationsService;
import com.project.demo.service.SmsService;
import com.project.demo.service.UserService;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户通知：(UserNotifications)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/user_notifications")
public class UserNotificationsController extends BaseController<UserNotifications, UserNotificationsService> {

    /**
     * 用户通知对象
     */
    @Autowired
    public UserNotificationsController(UserNotificationsService service) {
        setService(service);
    }

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    @Autowired
    private com.project.demo.service.MessageNotificationService messageNotificationService;


    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        try {
            Map<String,Object> paramMap = service.readBody(request.getReader());
            log.info("收到用户通知添加请求，参数: {}", paramMap);
            
            // 确保 participants 是整数类型
            if (paramMap.get("participants") != null) {
                try {
                    Object participantsObj = paramMap.get("participants");
                    if (participantsObj instanceof String) {
                        paramMap.put("participants", Integer.parseInt((String) participantsObj));
                    } else if (participantsObj instanceof Number) {
                        paramMap.put("participants", ((Number) participantsObj).intValue());
                    }
                } catch (NumberFormatException e) {
                    log.error("participants 格式错误: {}", paramMap.get("participants"), e);
                    return error(400, "参会用户ID格式错误");
                }
            }
            
            // 插入数据到数据库
            this.addMap(paramMap);
            log.info("用户通知数据插入成功");
            
            // 自动创建消息通知
            try {
                Integer notificationId = null;
                Integer userId = null;
                
                // 从参数中获取用户ID
                if (paramMap.get("participants") != null) {
                    Object participantsObj = paramMap.get("participants");
                    if (participantsObj instanceof Integer) {
                        userId = (Integer) participantsObj;
                    } else if (participantsObj instanceof Number) {
                        userId = ((Number) participantsObj).intValue();
                    } else {
                        userId = Integer.parseInt(participantsObj.toString());
                    }
                }
                
                // 从参数中获取主键ID（如果存在，说明是更新操作；如果不存在，需要查询刚插入的记录）
                if (paramMap.get("user_notifications_id") != null) {
                    Object idObj = paramMap.get("user_notifications_id");
                    if (idObj instanceof Integer) {
                        notificationId = (Integer) idObj;
                    } else if (idObj instanceof Number) {
                        notificationId = ((Number) idObj).intValue();
                    } else {
                        notificationId = Integer.parseInt(idObj.toString());
                    }
                } else {
                    // 如果是新增操作，需要查询刚插入的记录ID
                    // 使用更精确的查询条件：participants + 其他关键字段的组合
                    Map<String, String> query = new HashMap<>();
                    if (userId != null) {
                        query.put("participants", userId.toString());
                    }
                    // 添加其他唯一字段来确保查询到正确的记录
                    if (paramMap.get("conference_name") != null) {
                        String conferenceName = paramMap.get("conference_name").toString();
                        query.put("conference_name", conferenceName);
                    }
                    if (paramMap.get("notification_content") != null) {
                        String notificationContent = paramMap.get("notification_content").toString();
                        // 如果内容太长，只取前100个字符用于查询
                        if (notificationContent.length() > 100) {
                            notificationContent = notificationContent.substring(0, 100);
                        }
                        query.put("notification_content", notificationContent);
                    }
                    Map<String, String> config = new HashMap<>();
                    config.put("order", "create_time desc");
                    config.put("size", "1");
                    Query select = service.select(query, config);
                    Object resultObj = select != null && select.getResultList().size() > 0 ? select.getResultList().get(0) : null;
                    
                    if (resultObj instanceof UserNotifications) {
                        UserNotifications notification = (UserNotifications) resultObj;
                        notificationId = notification.getUser_notifications_id();
                        log.info("查询到刚插入的通知ID: {}", notificationId);
                    }
                }
                
                // 如果找到了记录ID，创建消息通知
                // 优先使用 paramMap 中的值（这些是前端提交的实际数据）
                if (notificationId != null && userId != null) {
                    String conferenceName = paramMap.get("conference_name") != null ? paramMap.get("conference_name").toString() : null;
                    String notificationContent = paramMap.get("notification_content") != null ? paramMap.get("notification_content").toString() : null;
                    String userName = paramMap.get("user_name") != null ? paramMap.get("user_name").toString() : null;
                    
                    log.info("创建消息通知 - userId: {}, notificationId: {}, conferenceName: {}, userName: {}", 
                            userId, notificationId, conferenceName, userName);
                    
                    messageNotificationService.createNotificationMessage(
                        userId,
                        notificationId,
                        conferenceName,
                        notificationContent,
                        userName
                    );
                    log.info("消息通知创建成功");
                } else {
                    log.warn("无法创建消息通知 - notificationId: {}, userId: {}", notificationId, userId);
                }
            } catch (Exception e) {
                log.error("创建通知消息失败", e);
                // 即使创建消息失败，也不影响主流程，只记录错误
            }
            
            return success(1);
        } catch (Exception e) {
            log.error("添加用户通知失败", e);
            return error(500, "添加用户通知失败: " + e.getMessage());
        }
    }

    /**
     * 发送通知短信
     */
    @PostMapping("/send_sms")
    public Map<String, Object> sendSms(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 从请求体或查询参数中获取 user_notifications_id
            String userNotificationsId = null;
            if (bodyMap != null && bodyMap.get("user_notifications_id") != null) {
                userNotificationsId = bodyMap.get("user_notifications_id").toString();
            } else {
                Map<String, String> query = service.readQuery(request);
                userNotificationsId = query.get("user_notifications_id");
            }
            
            if (userNotificationsId == null || userNotificationsId.isEmpty()) {
                return error(400, "user_notifications_id 不能为空");
            }

            // 查询通知信息
            Map<String, String> notificationQuery = new HashMap<>();
            notificationQuery.put("user_notifications_id", userNotificationsId);
            Map<String, String> notificationConfig = new HashMap<>(); // 传递空配置而不是 null
            Query notificationQueryResult = service.select(notificationQuery, notificationConfig);
            Object notificationObj = notificationQueryResult != null ? notificationQueryResult.getSingleResult() : null;
            
            if (notificationObj == null) {
                return error(404, "未找到通知信息");
            }

            UserNotifications notification;
            if (notificationObj instanceof UserNotifications) {
                notification = (UserNotifications) notificationObj;
            } else {
                return error(500, "数据格式错误");
            }

            // 获取用户手机号
            String phoneNumber = null;
            if (notification.getParticipants() != null) {
                Map<String, String> userQuery = new HashMap<>();
                userQuery.put("user_id", notification.getParticipants().toString());
                Query userQueryResult = userService.select(userQuery, null);
                Object userObj = userQueryResult != null ? userQueryResult.getSingleResult() : null;
                if (userObj instanceof User) {
                    User user = (User) userObj;
                    phoneNumber = user.getPhone();
                }
            }

            if (phoneNumber == null || phoneNumber.isEmpty()) {
                return error(400, "用户手机号为空，无法发送短信");
            }

            // 构建短信内容
            Map<String, String> smsParams = new HashMap<>();
            smsParams.put("notification_content", notification.getNotification_content() != null ? notification.getNotification_content() : "");
            smsParams.put("conference_name", notification.getConference_name() != null ? notification.getConference_name() : "");
            smsParams.put("meeting_time", notification.getMeeting_time() != null ? notification.getMeeting_time() : "");

            // 发送短信
            Map<String, Object> smsResult = smsService.sendSms(phoneNumber, null, smsParams);
            String smsContent = smsService.buildNotificationContent("通知", smsParams);
            smsResult.put("content", smsContent);

            log.info("发送用户通知短信 - 手机号: {}, 内容: {}", phoneNumber, smsContent);

            return success(smsResult);
        } catch (Exception e) {
            log.error("发送用户通知短信失败", e);
            return error(500, "发送短信失败: " + e.getMessage());
        }
    }

}
